package com.party.mobile.web.controller.crowdfund;

import com.google.common.base.Strings;
import com.party.authorization.annotation.Authorization;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.activity.Activity;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.counterfoil.CounterfoilBusiness;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.crowdfund.EventGradation;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.help.Help;
import com.party.core.model.help.HelpOutput;
import com.party.core.model.member.Member;
import com.party.core.model.system.TargetType;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.counterfoil.ICounterfoilBusinessService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IEventGradationService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.help.IHelpService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.system.ISysConfigService;
import com.party.mobile.biz.crowdfund.CrowdfundActivityBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.file.FileBizService;
import com.party.mobile.biz.member.MemberBizService;
import com.party.mobile.web.annotation.SessionToken;
import com.party.mobile.web.annotation.VisitCollect;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.crowdfund.input.ApplyInput;
import com.party.mobile.web.dto.crowdfund.output.ActivityDetailOutput;
import com.party.mobile.web.dto.crowdfund.output.ActivityGetOutput;
import com.party.mobile.web.dto.crowdfund.output.TabDataOutput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.login.output.MemberOutput;
import com.party.mobile.web.interceptor.TokenInterceptor;
import com.vdurmont.emoji.EmojiParser;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 众筹活动控制器
 * Created by wei.li
 *
 * @date 2017/2/24 0024
 * @time 17:24
 */

@Controller
@RequestMapping(value = "crowdfund/activity")
public class CrowdfundActivityController {

    protected static Logger logger = LoggerFactory.getLogger(CrowdfundActivityController.class);


    @Autowired
    private CrowdfundActivityBizService crowdfundActivityBizService;

    @Autowired
    private CurrentUserBizService currentUserBizService;

    @Autowired
    private MemberBizService memberBizService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;
    @Resource
    private TokenInterceptor tokenInterceptor;

    @Autowired
    private IHelpService helpService;
    @Autowired
    private ICounterfoilService counterfoilService;

    @Autowired
    private IEventGradationService eventGradationService;

    @Autowired
    private ICounterfoilBusinessService counterfoilBusinessService;

    /**
     * 众筹项目详情
     *
     * @param id 编号
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "detail")
    @VisitCollect(module = TargetType.ZC_ACTIVITY)
    public AjaxResult detail(String id, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        if (Strings.isNullOrEmpty(id)) {
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription("活动编号不能为空");
            return ajaxResult;
        }
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        ActivityDetailOutput activityDetailOutput = null;
        try {
            activityDetailOutput = crowdfundActivityBizService.detail(id, currentUser, null);
            CrowdfundEvent crowdfundEvent = crowdfundEventService.getCorwdfundByActivityId(id);
            Activity activity = new Activity();
            activity.setEventId(crowdfundEvent.getId());
            List<Activity> list = activityService.list(activity);
            Integer joinNum = 0;//这个主题下的所有报名数
            for (Activity activity1 : list) {
                joinNum += activity1.getJoinNum();
            }
            List<Counterfoil> counterfoils = counterfoilService.findByBusinessId(crowdfundEvent.getId(), Constant.BUSINESS_TYPE_CROWDFUND);
            Integer limitNum = 0;//这个主题一共限制多少人报名
            for (Counterfoil counterfoil : counterfoils) {
                limitNum += counterfoil.getLimitNum();
            }
            if(counterfoils.size()>0){
                Counterfoil counterfoil = counterfoils.get(0);
                activityDetailOutput.setPrice(counterfoil.getPayment());
            }
            activityDetailOutput.setLimitNum(limitNum);
            activityDetailOutput.setJoinNum(joinNum);
            activityDetailOutput.setCounterfoils(counterfoils);

            if (StringUtils.isNotEmpty(activityDetailOutput.getMyProjectId())) {
                Project project = projectService.get(activityDetailOutput.getMyProjectId());
                if (project != null) {
                    activityDetailOutput.setPayType(project.getPayType());//设置众筹类型标识
                }
            }
            String filePath = fileBizService.getUploadCIPath(activityDetailOutput.getAuthorId(), "zcActivity");
            // 众筹项目详情二维码
            String detailFileName = "detail_" + activityDetailOutput.getId();
            String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
            activityDetailOutput.setQrCodeUrl(detailQrCodeUrl);
        } catch (BusinessException be) {
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("众筹项目详情异常", e);
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }

        ajaxResult.setSuccess(true);
        ajaxResult.setData(activityDetailOutput);
        return ajaxResult;
    }

    /**
     * 众筹项目详情
     *
     * @param id 编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "detail2")
    @VisitCollect(module = TargetType.ZC_ACTIVITY)
    public AjaxResult detail2(String id, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        if (Strings.isNullOrEmpty(id)) {
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription("活动编号不能为空");
            return ajaxResult;
        }
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        ActivityDetailOutput activityDetailOutput = null;
        try {
            activityDetailOutput = crowdfundActivityBizService.detail(id, currentUser, null);
            Project project = projectService.get(activityDetailOutput.getMyProjectId());
            if (project != null)
                activityDetailOutput.setPayType(project.getPayType());//设置众筹类型标识
            String filePath = fileBizService.getUploadCIPath(activityDetailOutput.getAuthorId(), "zcActivity");
            // 众筹项目详情二维码
            String detailFileName = "detail_" + activityDetailOutput.getId();
            String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
            activityDetailOutput.setQrCodeUrl(detailQrCodeUrl);
        } catch (BusinessException be) {
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("众筹项目详情异常", e);
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }

        ajaxResult.setSuccess(true);
        ajaxResult.setData(activityDetailOutput);
        return ajaxResult;
    }


    /**
     * 获取活动
     *
     * @param id 编号
     * @return 输出视图
     */
    @ResponseBody
    @RequestMapping(value = "get")
    @VisitCollect(module = TargetType.ZC_ACTIVITY)
    public AjaxResult get(String id, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        if (Strings.isNullOrEmpty(id)) {
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription("活动编号不能为空");
            return ajaxResult;
        }

        boolean isConvertBase64 = sysConfigService.isConvertBase64();
        Activity activity = activityService.get(id);
        ActivityGetOutput activityGetOutput = ActivityGetOutput.transform(activity);
        activityGetOutput.setOrgId(activity.getMember());
        if (StringUtils.isNotEmpty(activityGetOutput.getCrowdDeclaration())) {
            if (isConvertBase64) {
                activityGetOutput.setCrowdDeclaration(StringUtils.decodeBase64New(activityGetOutput.getCrowdDeclaration()));
            } else {
                activityGetOutput.setCrowdDeclaration(EmojiParser.parseToUnicode(activityGetOutput.getCrowdDeclaration()));
            }
        }
        if (StringUtils.isNotEmpty(activityGetOutput.getRepresentDeclaration())) {
            if (isConvertBase64) {
                activityGetOutput.setRepresentDeclaration(StringUtils.decodeBase64New(activityGetOutput.getRepresentDeclaration()));
            } else {
                activityGetOutput.setRepresentDeclaration(EmojiParser.parseToUnicode(activityGetOutput.getRepresentDeclaration()));
            }
        }
        tokenInterceptor.getToken(ajaxResult);
        ajaxResult.setSuccess(true);
        ajaxResult.setData(activityGetOutput);//对于直接付款众筹会返回一个价格
        return ajaxResult;
    }


    /**
     * 手机端众筹报名入口
     *
     * @param applyInput
     * @param payType
     * @param result
     * @param request
     * @return
     */
    @Authorization
    @ResponseBody
    @SessionToken(verify = true)
    @RequestMapping(value = "apply")
    public AjaxResult apply(@Validated ApplyInput applyInput, BindingResult result,
                            HttpServletRequest request, Integer payType, String paperId) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            //数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErrors = result.getAllErrors();
                String description = allErrors.get(0).getDefaultMessage();
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, description);
            }
            Counterfoil counterfoil = counterfoilService.get(paperId);
            if (null == counterfoil) {
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "票据不存在");
            } else {
                //票种数量
                int limitNumDb = counterfoil.getLimitNum();
                //已购数量
                int joinNumDb = counterfoil.getJoinNum();
                if (limitNumDb == joinNumDb) {
                    throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "该票种已卖完");
                }
            }
            if (StringUtils.isNotEmpty(applyInput.getDeclaration())) {
                if (sysConfigService.isConvertBase64()) {
                    applyInput.setDeclaration(StringUtils.encodeBase64(applyInput.getDeclaration()));
                } else {
                    applyInput.setDeclaration(EmojiParser.parseToAliases(applyInput.getDeclaration()));
                }
            }


            CurrentUser currentUser = memberBizService.bindPhoneBiz2(applyInput.getMobile(), applyInput.getVerifyCode(),
                    applyInput.getCountryCode(), request);
            //如果字段为空 更新必要的用户信息
            Member curMember
                    = memberBizService.updateImportantInfo2(ApplyInput.transformMember(applyInput), memberService.get(currentUser.getId()));
            MemberOutput memberOutput = memberBizService.getLoginMember(curMember);

            //报名
            Map<String, Object> map = crowdfundActivityBizService.apply(applyInput, currentUser.getId(), payType, counterfoil);


            Boolean isApply = (Boolean) map.get("isApply");//是否已经报名
            if(!isApply){
                String projectId = (String) map.get("id");
                String memberId = currentUser.getId();
                new Thread(() -> crowdfundActivityBizService.dealCrowdApply(applyInput, memberId, projectId, payType)).start();
            }
            map.put("member", memberOutput);
            ajaxResult.setSuccess(true);
            ajaxResult.setData(map);
            return ajaxResult;
        } catch (BusinessException be) {
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setDescription("未知错误");
            logger.error("发起众筹异常", e);
            return ajaxResult;
        }
    }


    /**
     * 是否报名过众筹主题
     *
     * @param id      活动编号
     * @param request 请求参数
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "isApplyEvent")
    public AjaxResult isApplyEvent(String id, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        boolean isApply;
        try {
            isApply = crowdfundEventService.isApplyEvent(id, currentUser.getId());
        } catch (Exception e) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("服务器异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(isApply);
        return ajaxResult;
    }

    /**
     * 人员列表tab块
     *
     * @param targetId 众筹项目编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "tabData")
    public AjaxResult tabData(String targetId) {
        AjaxResult ajaxResult = new AjaxResult(true);
        TabDataOutput tabDataOutput;
        try {
            tabDataOutput = crowdfundActivityBizService.tabData(targetId);
        } catch (Exception e) {
            logger.error("人员列表tab块数据异常", e);
            ajaxResult.setSuccess(false);
            return ajaxResult;
        }
        ajaxResult.setData(tabDataOutput);
        return ajaxResult;
    }

    /**
     * 人员列表tab块
     *
     * @param targetId 众筹项目编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "newTabData")
    public AjaxResult newTabData(String targetId, String relationId) {
        AjaxResult ajaxResult = new AjaxResult(true);
        TabDataOutput tabDataOutput;
        try {
            tabDataOutput = crowdfundActivityBizService.newTabData(targetId, relationId);
        } catch (Exception e) {
            logger.error("人员列表tab块数据异常", e);
            ajaxResult.setSuccess(false);
            return ajaxResult;
        }
        ajaxResult.setData(tabDataOutput);
        return ajaxResult;
    }


    /***
     * 根据后台设置查询所有的报名者  H5个人众筹页改版 2018-12-20
     * @param targetId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "projectList")
    public AjaxResult projectList(String targetId, Page page) {
        try {
            if (StringUtils.isEmpty(targetId)) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目id不能为空");
            }
            Activity activity = activityService.get(targetId);
            if (2 == activity.getPersonalPopularPageState()) {
                //2代表不显示报名人员
                return AjaxResult.success("不显示报名人员");
            }
            if (1 == activity.getPersonalPopularPageState()) {
                //1代表显示该项目报名人员
                List<Project> projectList = projectService.getProjectByActivityId(targetId, page);
                for (Project project : projectList) {
                    Double div = BigDecimalUtils.div(project.getActualAmount(),
                            project.getTargetAmount(), 2);
                    project.setPercentage(div.floatValue());
                }
                return AjaxResult.success(projectList, page);
            }

            if (0 == activity.getPersonalPopularPageState()) {
                //0代表显示所属主题报名人员
                List<Project> projectList = projectService.queryProjectByTargetId(activity.getEventId(), page);
                for (Project project : projectList) {
                    Double div = BigDecimalUtils.div(project.getActualAmount(),
                            project.getTargetAmount(), 2);
                    project.setPercentage(div.floatValue());
                }
                return AjaxResult.success(projectList, page);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("同行戈友人员列表异常：targetId-{}", targetId, e);
            return AjaxResult.error();
        }
    }


    /***
     * 个人排行榜  H5个人众筹页改版 2018-12-20   分页
     * @type type 0代表速度榜，1代表人气榜，2代表财富榜
     * @activityId activityId  项目id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "personalList")
    public AjaxResult personalList(String type, Page page, String targetId) {
        try {
            if (StringUtils.isEmpty(targetId) || targetId.equals("undefined")) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目id不能为空");
            }
            if (StringUtils.isEmpty(type)) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "排行榜类型不能为空");
            }
            CrowdfundEvent crowdfundEvent = crowdfundEventService.getCorwdfundByActivityId(targetId);
            if (1 == crowdfundEvent.getPersonalRanking()) {
                //说明是自定义显示的人数
                final int limit = page.getLimit();
                if (crowdfundEvent.getPeopleNum() < page.getLimit() * page.getPage()) {
                    page.setLimit(crowdfundEvent.getPeopleNum() - (page.getLimit() * page.getPage() - page.getLimit()));
                    if (page.getLimit() == 0) {
                        return AjaxResult.success("没有数据啦");
                    }
                    List<Project> projectList = projectService.popularityList(targetId, page, type);
                    page.setLimit(limit);
                    if (page.getPage() > 1) {
                        projectList = getToProjectList(page, projectList);
                    }
                    return AjaxResult.success(projectList, page);
                } else {
                    List<Project> projectList = projectService.popularityList(targetId, page, type);
                    if (page.getPage() > 1) {
                        projectList = getToProjectList(page, projectList);
                    }
                    return AjaxResult.success(projectList, page);
                }
            } else if (0 == crowdfundEvent.getPersonalRanking()) {
                List<Project> projectList = projectService.popularityList(targetId, page, type);
                if (page.getPage() > 1) {
                    projectList = getToProjectList(page, projectList);
                }
                for (Project project : projectList) {
                    if (project.getUseTime() < 0) {
                        project.setUseTime(Long.valueOf(60000));
                    }
                }
                return AjaxResult.success(projectList, page);
            } else {
                return AjaxResult.success("不显示排行榜");
            }
        } catch (Exception e) {
            logger.error("个人排行榜分页异常：type-{}，targetId-{}", type, targetId, e);
            return AjaxResult.error();
        }
    }


    /***
     * 个人排行榜  H5个人众筹页改版 2018-12-20   个人信息
     * @type type 0代表速度榜，1代表人气榜，2代表财富榜
     * @targetId targetId  项目id
     * @return
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "personal")
    public AjaxResult personal(String targetId, HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        try {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.getCorwdfundByActivityId(targetId);
            if (crowdfundEvent == null) {
                return AjaxResult.success("个人排行榜个人信息   有问题");
            }
            if (2 == crowdfundEvent.getPersonalRanking()) {
                return AjaxResult.success("不显示个人排行榜个人信息");
            }
            Map<String, Object> projectMap = new HashMap<>();
            //速度
            Project speedProject = projectService.popularity(targetId, "0", currentUser.getId());
            //人气
            Project popularityProject = projectService.popularity(targetId, "1", currentUser.getId());
            //财富
            Project wealthProject = projectService.popularity(targetId, "2", currentUser.getId());
            if (null == speedProject) {
                speedProject = projectService.getByMemberId(targetId, currentUser.getId());
            }
            if (speedProject != null && speedProject.getUseTime() < 0) {
                speedProject.setUseTime(Long.valueOf(60000));
            }
            projectMap.put("speedProject", speedProject);
            projectMap.put("popularityProject", popularityProject);
            projectMap.put("wealthProject", wealthProject);
            return AjaxResult.success(projectMap);
        } catch (Exception e) {
            logger.error("个人排行榜个人信息异常--targetId：{}，memberId：{}", targetId, currentUser.getId(), e);
            return AjaxResult.error();
        }
    }


    /***
     * 个人排行榜  H5个人众筹页改版 2018-12-20   分页
     * @param page
     * @param list
     * @return
     */
    public List<Project> getToProjectList(Page page, List<Project> list) {
        for (Project project : list) {
            Integer ranking = project.getRanking();
            int current = page.getPage();
            int size = page.getLimit();
            project.setRanking((current - 1) * size + ranking);

        }
        return list;
    }


    /***
     * 众筹攻略查询
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getPublicStrategy")
    public AjaxResult getPublicStrategy() {
        try {
            Help help = helpService.getPublicStrategy();
            if (StringUtils.isNotEmpty(help.getContent())) {
                String content = StringEscapeUtils.unescapeHtml4(help.getContent());
                help.setContent(content);
            }
            return AjaxResult.success(help);
        } catch (Exception e) {
            logger.error("众筹攻略查询异常", e);
            return AjaxResult.error();
        }
    }


    /***
     * 常见问题查询
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "commonProblemList")
    public AjaxResult commonProblemList(Page page) {
        try {
            List<HelpOutput> helpList = helpService.commonProblemList(page);
            List<HelpOutput> helpLists = new ArrayList<>();
            for (HelpOutput helpOutput : helpList) {
                if (!"众筹攻略".equals(helpOutput.getTitle())) {
                    helpLists.add(helpOutput);
                }
            }
            return AjaxResult.success(helpLists, page);
        } catch (Exception e) {
            logger.error("常见问题查询异常", e);
            return AjaxResult.error();
        }
    }

    /***
     * 常见问题二级分类详情查询
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "details")
    public AjaxResult details(String id) {
        try {
            Help help = helpService.get(id);
            if (StringUtils.isNotEmpty(help.getContent())) {
                String content = StringEscapeUtils.unescapeHtml4(help.getContent());
                help.setContent(content);
            }
            return AjaxResult.success(help);
        } catch (Exception e) {
            logger.error("常见问题二级分类详情查询异常", e);
            return AjaxResult.error();
        }
    }


    /**
     * 众筹项目详情
     *
     * @param id 编号
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "gradation/detail")
    @VisitCollect(module = TargetType.ZC_ACTIVITY)
    public AjaxResult gradationDetail(String id, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        if (Strings.isNullOrEmpty(id)) {
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription("活动编号不能为空");
            return ajaxResult;
        }
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        ActivityDetailOutput activityDetailOutput = null;
        try {
            activityDetailOutput = crowdfundActivityBizService.gradationDetail(id, currentUser, null);
            if (StringUtils.isNotEmpty(activityDetailOutput.getMyProjectId())) {
                Project project = projectService.get(activityDetailOutput.getMyProjectId());
                if (project != null) {
                    activityDetailOutput.setPayType(project.getPayType());//设置众筹类型标识
                }
            }

            String filePath = fileBizService.getUploadCIPath(activityDetailOutput.getAuthorId(), "zcActivity");
            // 众筹项目详情二维码
            String detailFileName = "target_multi_detail" + activityDetailOutput.getId();
            String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
            activityDetailOutput.setQrCodeUrl(detailQrCodeUrl);
        } catch (BusinessException be) {
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("众筹项目详情异常", e);
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }

        ajaxResult.setSuccess(true);
        ajaxResult.setData(activityDetailOutput);
        return ajaxResult;
    }

    /**
     * 众筹项目详情
     *
     * @param id 编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "gradation/detail2")
    @VisitCollect(module = TargetType.ZC_ACTIVITY)
    public AjaxResult gradationDetail2(String id, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        if (Strings.isNullOrEmpty(id)) {
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription("活动编号不能为空");
            return ajaxResult;
        }
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        ActivityDetailOutput activityDetailOutput = null;
        try {
            activityDetailOutput = crowdfundActivityBizService.gradationDetail(id, currentUser, null);
            Project project = projectService.get(activityDetailOutput.getMyProjectId());
            if (project != null){
                activityDetailOutput.setPayType(project.getPayType());//设置众筹类型标识
            }

            String filePath = fileBizService.getUploadCIPath(activityDetailOutput.getAuthorId(), "zcActivity");
            // 众筹项目详情二维码
            String detailFileName = "target_multi_detail" + activityDetailOutput.getId();
            String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
            activityDetailOutput.setQrCodeUrl(detailQrCodeUrl);
        } catch (BusinessException be) {
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("众筹项目详情异常", e);
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }

        ajaxResult.setSuccess(true);
        ajaxResult.setData(activityDetailOutput);
        return ajaxResult;
    }


    /**
     * 手机端众筹报名入口__多场
     *
     * @param applyInput
     * @param payType
     * @param result
     * @param request
     * @return
     */
    @Authorization
    @ResponseBody
    @SessionToken(verify = true)
    @RequestMapping(value = "gradation/apply")
    public AjaxResult gradationApply(@Validated ApplyInput applyInput, BindingResult result, HttpServletRequest request, Integer payType) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            //数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErrors = result.getAllErrors();
                String description = allErrors.get(0).getDefaultMessage();
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, description);
            }
            if (StringUtils.isNotEmpty(applyInput.getDeclaration())) {
                if (sysConfigService.isConvertBase64()) {
                    applyInput.setDeclaration(StringUtils.encodeBase64(applyInput.getDeclaration()));
                } else {
                    applyInput.setDeclaration(EmojiParser.parseToAliases(applyInput.getDeclaration()));
                }
            }
            CurrentUser currentUser = memberBizService.bindPhoneBiz2(applyInput.getMobile(), applyInput.getVerifyCode(),
                    applyInput.getCountryCode(), request);
            //如果字段为空 更新必要的用户信息
            Member curMember
                    = memberBizService.updateImportantInfo2(ApplyInput.transformMember(applyInput), memberService.get(currentUser.getId()));
            MemberOutput memberOutput = memberBizService.getLoginMember(curMember);

            //报名
            Map<String, Object> map = crowdfundActivityBizService.gradationApply(applyInput, currentUser.getId(), payType);

            Boolean isApply = (Boolean) map.get("isApply");//是否已经报名
            if(!isApply){
                String projectId = (String) map.get("id");
                String memberId = currentUser.getId();
                new Thread(() -> crowdfundActivityBizService.dealCrowdApply(applyInput, memberId, projectId, payType)).start();
            }

            map.put("member", memberOutput);
            ajaxResult.setSuccess(true);
            ajaxResult.setData(map);
            return ajaxResult;
        } catch (BusinessException be) {
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setDescription("未知错误");
            logger.error("发起众筹异常_多场", e);
            return ajaxResult;
        }
    }

    /**
     * 获取活动__多场众筹
     *
     * @param id 编号
     * @return 输出视图
     */
    @ResponseBody
    @RequestMapping(value = "gradation/get")
    @VisitCollect(module = TargetType.ZC_ACTIVITY)
    public AjaxResult gradationGet(String id, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        if (Strings.isNullOrEmpty(id)) {
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription("活动编号不能为空");
            return ajaxResult;
        }

        boolean isConvertBase64 = sysConfigService.isConvertBase64();
        Activity activity = activityService.get(id);
        ActivityGetOutput activityGetOutput = ActivityGetOutput.transform(activity);
        activityGetOutput.setOrgId(activity.getMember());
        if (StringUtils.isNotEmpty(activityGetOutput.getCrowdDeclaration())) {
            if (isConvertBase64) {
                activityGetOutput.setCrowdDeclaration(StringUtils.decodeBase64New(activityGetOutput.getCrowdDeclaration()));
            } else {
                activityGetOutput.setCrowdDeclaration(EmojiParser.parseToUnicode(activityGetOutput.getCrowdDeclaration()));
            }
        }
        if (StringUtils.isNotEmpty(activityGetOutput.getRepresentDeclaration())) {
            if (isConvertBase64) {
                activityGetOutput.setRepresentDeclaration(StringUtils.decodeBase64New(activityGetOutput.getRepresentDeclaration()));
            } else {
                activityGetOutput.setRepresentDeclaration(EmojiParser.parseToUnicode(activityGetOutput.getRepresentDeclaration()));
            }
        }


        Date endTime_gradation = null;
        try {
            EventGradation ongoingGradation = eventGradationService.findOngoingGradation(activity.getEventId());
            if(null==ongoingGradation){
                //最后阶段主题
                ongoingGradation = eventGradationService.getTheLastGradation(activity.getEventId());
            }
            endTime_gradation = ongoingGradation.getEndTime();
        }catch (Exception e){
            logger.info("多阶段众筹__获取正在进行主题的结束时间,获取失败", e.getMessage());
        }
        activityGetOutput.setEndTime(endTime_gradation);
        tokenInterceptor.getToken(ajaxResult);
        ajaxResult.setSuccess(true);
        ajaxResult.setData(activityGetOutput);//对于直接付款众筹会返回一个价格
        return ajaxResult;
    }


    /**
    * @Author hzq
    * @Description //初始化票据
    * @Date 16:56 2019/6/25
    * @param
    * @return
    **/
    @ResponseBody
    @RequestMapping(value = "initPaper")
    public AjaxResult initPaper() {
        try {
            List<CrowdfundEvent> list = crowdfundEventService.list(new CrowdfundEvent());
            Activity activity = new Activity();
            for (CrowdfundEvent crowdfundEvent : list) {
                if(null == crowdfundEvent.getLimitNum()){
                    continue;
                }
                Counterfoil counterfoil = new Counterfoil();
                counterfoil.setBusinessId(crowdfundEvent.getId());
                counterfoil.setCreateBy(crowdfundEvent.getCreateBy());
                counterfoil.setPayment(crowdfundEvent.getPrice());
                counterfoil.setName(crowdfundEvent.getName());
                counterfoil.setBusinessType(Constant.BUSINESS_TYPE_CROWDFUND);
                counterfoil.setSort(1);
                activity.setEventId(crowdfundEvent.getId());
                activity.setDelFlag("0");
                Integer joinNum = 0;
                Integer limitNum = 0;
                List<Activity> list1 = activityService.list(activity);
                for (Activity activity1 : list1) {
                    joinNum += activity1.getJoinNum();
                    limitNum += activity1.getLimitNum();
                }
                counterfoil.setJoinNum(joinNum);
                counterfoil.setLimitNum(limitNum);
                counterfoilService.insert(counterfoil);
                joinNum = 0;
                limitNum = 0;
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("初始化票据异常", e);
            return AjaxResult.error();
        }
    }

    /**
     * @Author hzq
     * @Description //初始化众筹和票据的关系
     * @Date 16:56 2019/6/25
     * @param
     * @return
     **/
    @ResponseBody
    @RequestMapping(value = "initPaperBusiness")
    public AjaxResult initPaperBusiness() {
        try {
            CrowdfundEvent crowdfundEvent = new CrowdfundEvent();
            crowdfundEvent.setProgress(1);
            List<CrowdfundEvent> list = crowdfundEventService.list(crowdfundEvent);
            for (CrowdfundEvent event : list) {
                List<Counterfoil> byBusinessId = counterfoilService.findByBusinessId(event.getId(), Constant.BUSINESS_TYPE_CROWDFUND);
                if(byBusinessId.size()>0){
                    Counterfoil counterfoil = byBusinessId.get(0);
                    List<Project> byEventId = projectService.findByEventId(event.getId());
                    for (Project project : byEventId) {
                        CounterfoilBusiness counterfoilBusiness = new CounterfoilBusiness();
                        counterfoilBusiness.setCounterfoilId(counterfoil.getId());
                        counterfoilBusiness.setBusinessId(project.getId());
                        counterfoilBusinessService.insert(counterfoilBusiness);
                    }
                }
            }

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("初始化票据异常", e);
            return AjaxResult.error();
        }
    }
}
